package org.sang.service;

import com.alibaba.fastjson.JSON;
import org.sang.beans.User;
import org.sang.utils.MD5;
import org.sang.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class TokenService {
    @Resource
    private RedisUtil redisUtil;

    /**
    /**
     * 生成Token字符串
     * 编辑PC-USERCOOE-USERId-CREATIONDATE-RONDEM
     */
    public  String generateToken(String userAgent, User user) throws  Exception{
        StringBuffer str=new StringBuffer();
        str.append("token:");
        str.append("PC-");
        str.append(MD5.getMd5(user.getUsername(),32)+"-");
        str.append(user.getId().toString()+"-");
        str.append(new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date())+"-");
        str.append(MD5.getMd5(userAgent,6));
        return str.toString();
    }

    /**
     * 保存Token至Redis  保存 Token的信息
     * @param token
     * @param user
     * @throws Exception
     */
    public void save(String token,User user)throws  Exception{
        System.err.println("userID:"+user.getId());
        if(token.startsWith("token:"+"PC-")){
            redisUtil.setex(token,JSON.toJSONString(user),2*60*60);
        }else{  //手机认增信息永不失效
            redisUtil.set(token,JSON.toJSONString(user));
        }
    }

public void delete(String token) throws Exception{
        redisUtil.delete(token);
    }

}
